package dao.Implementation;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import Donnees.Pays;
import Donnees.Ville;
import Util.HibernateUtil;
import dao.Interfaces.IVilleDAO;

public class VilleDAO implements IVilleDAO {
	public VilleDAO() {
	}

	public List<Ville> selectAll() {
		List<Ville> listeVille = new ArrayList<Ville>();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		listeVille.addAll(session.createQuery("from Ville").list());

		session.flush();
		tx.commit();
		session.close();

		return listeVille;
	}

	public long insert(Ville v, String nomPays) {
		Ville villeTemp = v;
		Long msgId;
		
		PaysDAO paysDao = new PaysDAO();
		Pays p = paysDao.getByName(nomPays);
		
		villeTemp.setPays(p);
		villeTemp.setPaysId(p.getId());
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		msgId = (Long) session.save(villeTemp);

		session.flush();
		tx.commit();
		session.close();

		return msgId;
	}

	public int delete(Ville v) {
		Ville villeTemp = v;
		int retour;

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		retour = session.createQuery(
				"delete from Ville where nom='" + villeTemp.getNom() + "'")
				.executeUpdate();

		session.flush();
		tx.commit();
		session.close();

		return retour;
	}
}
